<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
function plant_structure_add_more_page(){
    return drupal_get_form('plant_structure_add_more_form');
}
function plant_structure_add_page($id) {
    return drupal_get_form('plant_structure_edit_form', $id);
}

function plant_structure_edit_page($id) {
    return drupal_get_form('plant_structure_edit_form', $id);
}

function plant_structure_edit_form($form, &$form_state) {
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    if (!empty($id)) {
        $record = nonghua_data_load('plant_structure', 'plant_structure_id', $id);
        if (empty($record)) {
            drupal_set_message(t('种植结构数据不存在！'), 'status', FALSE);
            return $form;
        }

        $form_state['id'] = $id;
    }
// 判断用户角色
    if(!nonghua_user_access('plant_structure', 'view', $id, !empty($record) ? $record->author_uid:0, 0) ){
        drupal_set_message(t('您没有权限查看本条数据！'), 'status', FALSE);
        return $form;
    }
    $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state,isset($record) && !empty($record)?$record->addr_id:'');
    $form['address'] = _insert_address_selection_form($form, $form_state,'address', 5, TRUE, !empty($record)?$record->addr_id:'','省,市,县必填');

    $form['plant_structure'] = array(
//        '#type' => 'fieldset',
//        '#title' => '种植结构',
//        '#collapsed' => false,
//        '#collapsible' => true,
    );

    for ($i = 0; $i < variable_get("plant_structure_years_total", 5); $i++) {
        $year_options[date('Y')-$i] = date('Y')-$i;
    }
    $form['plant_structure']['year'] = array(
        '#title' =>  '年度',
        '#type' => 'select',
        '#validated' => TRUE,
        '#required' => TRUE,
        '#options' => $year_options,
        '#default_value' => !empty($record) ? $record->year:'',
    );
    $form['plant_structure']['plant']= _insert_plant_selection_form($form,$form_state,!empty($record) ? $record->plant_id:'');


    $form['plant_structure']['area'] = array(
        '#type' => 'textfield',
        '#title' => '种植面积（亩）',
//        '#size' => 32,
//        '#maxlength' => 8,
        '#required' => TRUE,
        '#default_value' => !empty($record) ? $record->quantity:'',
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => arg(1) == 'edit' ? '修改' : '添加',
        '#access' =>  nonghua_user_access('plant_structure', 'edit', $id, !empty($record) ? $record->author_uid:0, 0) ,
    );
    return $form;
}

function plant_structure_edit_form_validate($form, &$form_state) {
    $empty = false;
    $empty = !_address_element_validate($form_state);
    if(empty($form_state['values']['plant'])){
        form_set_error('plant', '必须填写 农作物');
        $empty = true;
    }
    if(empty($form_state['values']['year'])){
        form_set_error('year', '必须填写 年份');
        $empty = true;
    }
    if(!empty($form_state['values']['area'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['area']) || (strlen(explode('.',$form_state['values']['area'])[0])>8)) {
            form_set_error('area', "种植面积格式错误");
        }
    }
    if(!empty($form_state['values']['plant'])){
        $plant_id = get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['plant'],false);
        if(empty($plant_id)){
            form_set_error('plant', "作物信息不存在！");
            $empty = true;
        }
    }
    if(!$empty && arg(1) === "add") {
        $address =  _get_address_id_from_autocomplete_select($form_state);
        $query = db_select('plant_structure', 's');
        $query->condition('s.addr_id',$address);
        $query->condition('s.plant_id',get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['plant'],false));
        $query->condition('s.year', $form_state['values']['year']);
        $query->fields('s');
        $record = $query->execute()->fetchAssoc();
        if (!empty($record)) {
            form_set_error('', '该地址的该农作物在'.$form_state['values']['year'].'年度'.'信息已存在！');
        }

    }
    if(!$empty && arg(1) === "edit") {
        $address =  _get_address_id_from_autocomplete_select($form_state);
        $query = db_select('plant_structure', 's');
        $query->condition('s.addr_id',$address);
        $query->condition('s.plant_id', get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['plant'],false));
        $query->condition('s.year', $form_state['values']['year']);
        $query->condition('s.plant_structure_id',$form_state['id'],'!=');
        $query->fields('s');
        $record = $query->execute()->fetchAssoc();
        if (!empty($record)) {
            form_set_error('', '该地址的该农作物在'.$form_state['values']['year'].'年度'.'信息已存在！');

        }
    }

}

function plant_structure_edit_form_submit($form, &$form_state) {
    global $user;
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    $address =  _get_address_id_from_autocomplete_select($form_state);
    if (arg(1) == 'add') { //add new plant_structure
        $nid = db_insert('plant_structure') // Table name no longer needs {}
        ->fields(array(
            'addr_id' => $address,
            'plant_id' =>get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['plant'],false),
            'year' => $form_state['values']['year'],
            'quantity' => $form_state['values']['area'],
            'author_uid' => $user->uid,
            'timestamp' => time(),))
            ->execute();
        if ($nid > 0) {
            drupal_set_message(t('添加成功！'), 'status', FALSE);
            drupal_goto('plant_structure/add/'.$nid);
        }
//        drupal_goto('plant_structure/list');
    } else {
        $nid = db_update('plant_structure') // edit exsting store. todo: update only modified fields
        ->fields(array(
            'addr_id' => $address,
            'plant_id' => get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['plant'],false),
            'year' => $form_state['values']['year'],
            'quantity' => $form_state['values']['area'],
//            'author_uid' => $user->uid,
            'timestamp' => time(),))
            -> condition('plant_structure_id',$id, '=')
            ->execute();
        if ($nid > 0) {
            drupal_set_message(t('修改成功！'), 'status', FALSE);
        }

//        drupal_goto('plant_structure/list');
    }
}


function plant_structure_add_more_form($form, &$form_state) {
     $form_state['insert'] = true;
    $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state,isset($record) && !empty($record)?$record->addr_id:'');
     $form['address'] = _insert_address_selection_form($form, $form_state,'address', 5, TRUE, '','省,市,县必填');
    for ($i = 0; $i < variable_get("plant_structure_years_total", 5); $i++) {
        $year_options[date('Y')-$i] = date('Y')-$i;
    }
    $form['year'] = array(
        '#title' =>  '年度',
        '#type' => 'select',
        '#validated' => TRUE,
        '#required' => TRUE,
        '#options' => $year_options,
    );
    $plants = db_select('plant', 'P')
        ->fields('P', array('plant_id', 'plant_name'))
        ->execute();
    $plant_options[''] = '请选择作物';
    foreach ($plants as $plant) {
        $plant_options[$plant->plant_id] = $plant->plant_name;
    }
    $role = user_access('manage plant');
    $form['plant_1'] = array(
        '#type' => 'select',
        '#title' => '作物',
        '#options' => $plant_options,
    );
    $form['area_1'] = array(
        '#type' => 'textfield',
        '#title' => '种植面积（亩）',
    );
    $form['plant_2'] = array(
        '#type' => 'select',
        '#title' => '作物',
        '#options' => $plant_options,
    );
    $form['area_2'] = array(
        '#type' => 'textfield',
        '#title' => '种植面积（亩）',
    );
    $form['plant_3'] = array(
        '#type' => 'select',
        '#title' => '作物',
        '#options' => $plant_options,
    );
    $form['area_3'] = array(
        '#type' => 'textfield',
        '#title' => '种植面积（亩）',
    );
    $form['plant_4'] = array(
        '#type' => 'select',
        '#title' => '作物',
        '#options' => $plant_options,
    );
    $form['area_4'] = array(
        '#type' => 'textfield',
        '#title' => '种植面积（亩）',
    );
    $form['plant_5'] = array(
        '#type' => 'select',
        '#title' => '作物',
        '#options' => $plant_options,
    );
    $form['area_5'] = array(
        '#type' => 'textfield',
        '#title' => '种植面积（亩）',
    );
    $form['plant_6'] = array(
        '#type' => 'select',
        '#title' => '作物',
        '#options' => $plant_options,
    );
    $form['area_6'] = array(
        '#type' => 'textfield',
        '#title' => '种植面积（亩）',
    );
    $form['plant_7'] = array(
        '#type' => 'select',
        '#title' => '作物',
        '#options' => $plant_options,
    );
    $form['area_7'] = array(
        '#type' => 'textfield',
        '#title' => '种植面积（亩）',
    );
    $form['plant_8'] = array(
        '#type' => 'select',
        '#title' => '作物',
        '#options' => $plant_options,
    );
    $form['area_8'] = array(
        '#type' => 'textfield',
        '#title' => '种植面积（亩）',
    );
    $form['plant_9'] = array(
        '#type' => 'select',
        '#title' => '作物',
        '#options' => $plant_options,
    );
    $form['area_9'] = array(
        '#type' => 'textfield',
        '#title' => '种植面积（亩）',
    );
    $form['plant_10'] = array(
        '#type' => 'select',
        '#title' => '作物',
        '#options' => $plant_options,
    );
    $form['area_10'] = array(
        '#type' => 'textfield',
        '#title' => '种植面积（亩）',
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => '添加',
    );
    return $form;
}

function plant_structure_add_more_form_validate($form, &$form_state){
    $empty = false;
    $empty = !_address_element_validate($form_state);
    if(empty($form_state['values']['year'])){
        form_set_error('year', '必须填写 年份');
        $empty = true;
    }
    for($i=1;$i<11;$i++){
        if(!empty($form_state['values']['area_'.$i])){
            $reg = '/^\d{1,8}(.\d{0,2})?$/';
            if(!preg_match ($reg, $form_state['values']['area_'.$i]) || (strlen(explode('.',$form_state['values']['area_'.$i])[0])>8)) {
                form_set_error('area_'.$i, "种植面积格式错误");
                $empty = true;
            }
        }
        $address =  _get_address_id_from_autocomplete_select($form_state);
        $query = db_select('plant_structure', 's');
        $query->condition('s.addr_id',$address);
        $query->condition('s.plant_id',$form_state['values']['plant_'.$i]);
        $query->condition('s.year', $form_state['values']['year']);
        $query->fields('s');
        $record = $query->execute()->fetchAssoc();
        if (!empty($record)) {
            form_set_error('', '该地址的该农作物在'.$form_state['values']['year'].'年度'.'信息已存在！');
            $empty = true;
        }
    }
}

function plant_structure_add_more_form_submit($form, &$form_state)
{
    global $user;
    $address =  _get_address_id_from_autocomplete_select($form_state);
    for($i=1;$i<11;$i++){
        if(!empty($form_state['values']['plant_'.$i]) && !empty($form_state['values']['area_'.$i])){
            $nid = db_insert('plant_structure')// Table name no longer needs {}
            ->fields(array(
                'addr_id' => $address,
                'plant_id' => $form_state['values']['plant_'.$i],
                'year' => $form_state['values']['year'],
                'quantity' => $form_state['values']['area_'.$i],
                'author_uid' => $user->uid,
                'timestamp' => time(),))
                ->execute();
        }
        if ($nid > 0) {
            drupal_set_message(t('添加成功！'), 'status', FALSE);
        }
    }
}